var privileges ;
var canUpdate = false;
var privilegeSet=false;

function qryUser() {
	//查询用户的修改权限
	privileges = checkUserPrivilege(['1240','1210','1220','1230','1250']);
	//用户权限判断
	if (privileges.result == "true") {
		var add="";
		var del="";
		var adds="";
		var refresh='<a class="btn" href="javascript:location.reload()"><i class="icon-refresh"></i>刷新</a>';
		$(privileges.data).each(function(ix, ite) {
			$("#operator a").remove();
			if (ite.code=="1210" && ite.value=="1"){
				//新增用户
				add='<a class="btn" href="addUserInfo.jsp"><i class="icon-plus"></i>新增用户</a> ';
			}
			if (ite.code=="1220" && ite.value=="1"){
				//删除用户
				del = '<a class="btn" href="javascript:removeAllUser();"><i class="icon-remove"></i>删除用户</a>';
			}
			if (ite.code=="1230" && ite.value=="1"){
				//批量新增用户 --href="javascript:location.reload()"
				adds = '<a class="btn" data-toggle="modal"  data-target="#myModal1" ><i class="icon-plus"></i>批量新增</a>';
				$('#myModal1').on('show.bs.modal', function () {
					  // 执行一些动作...
					//初始化fileinput控件（第一次初始化）
		            initFileInput("file-Portrait1", "userAction!uploadFile.action");
		            //initFileInput("file-Portrait1");
					});
			}
			if (ite.code=="1240" && ite.value=="1"){
				//修改用户
				canUpdate = true;
			}
			if (ite.code=="1250" && ite.value=="1"){
				//修改用户
				privilegeSet = true;
			}
		});
		$("#operator").prepend(add+del+adds+refresh);
	}else {
		alert("查询失败"+data.msg);
	}
	
	var searchtype = $("#search-type option:selected").val();//查询类型
	var account;
	var companyName;
	var partyName;
	if (searchtype=='company') {
		companyName = $("#n-keyword-input").val() ;
	} else if(searchtype=='name') {
		partyName = $("#n-keyword-input").val() ;
	} else if(searchtype=='account'){
		account = $("#n-keyword-input").val() ;
		searchtype = 'user';
	}
	
	var jsondata={};
	jsondata.qryType = searchtype;
	jsondata.account = account;
	jsondata.partyName = partyName;
	jsondata.companyName = companyName;
	$.post(
		"userAction!qryUserList.action",
		{comingParams : JSON.stringify(jsondata)},
		function(data){
			data = eval("("+data+")");
			if(data!=null&&data.result=="true"){
				$("#demo").myPagination({
				currPage: 1,
				pageSize: 5,
				pageCount:data.pageInfo.totalPageCount,
				ajax:{
					on: true,                        //开启状态
					url: "userAction!qryUserList.action",
		            dataType: 'json',                //返回类型
		            callback:'callBack',
		            param:{"on":true, comingParams : JSON.stringify(jsondata)},
		            ajaxStart: function() {
		                return false;
		            },onClick:function(page){
		            	alert(page);
		            }
				}
			});
			}else{
				alert("查询失败:"+data.msg);
			}
		}
	);
}

function callBack(data){
	$("#listTable>tbody").children().remove();
	data = eval("("+data+")");
	$(data.pageInfo.dataList).each(function(ix,ite){
		var trStr = '<tr>';
		var strValue = ite.userId 
		if (!StrUtil.isEmpty(ite.partyInfo)){
			strValue = strValue + ";" + StrUtil.strnull(ite.partyInfo.partyInfoId);
		}else{
			strValue = strValue + ";";
		}
		
		if (!StrUtil.isEmpty(ite.address)){
			strValue = strValue + StrUtil.strnull(ite.address.addressId);
		}
		trStr += '<td class="with-checkbox"><input type="checkbox" name="check" value="'+strValue +'" /></td>';
		trStr += '<td>'+ite.account+'</td>';
		var userName;
		if (!StrUtil.isEmpty(ite.partyInfo)) {
			trStr += '<td>'+StrUtil.strnull(ite.partyInfo.partyName)+'</td>';
			userName = StrUtil.strnull(ite.partyInfo.partyName);
		} else {
			trStr += '<td></td>';
		}
		
		if (!StrUtil.isEmpty(ite.partyInfo)) {
			trStr += '<td>'+StrUtil.strnull(ite.partyInfo.mobile)+'</td>';
		} else {
			trStr += '<td></td>';
		}
		
		if(ite.userType =='10') {
			trStr += '<td>平台用户</td>';
		} else if (ite.userType == '11') {
			trStr += '<td>物业用户</td>';
		} else if (ite.userType == '12') {
			trStr += '<td>业主</td>';
		}else {
			trStr += '<td>未知</td>';
		}
		
		if (!StrUtil.isEmpty(ite.company)){
			trStr += '<td>'+StrUtil.strnull(ite.company.companyName)+'</td>';
		}else{
			trStr += '<td>'+'</td>';
		}
		
		trStr += '<td>' + StrUtil.strnull(ite.statusName) + '</td>';
		/*if (ite.statusCd =='1000') {
			trStr += '<td>生效</td>';
		} else {
			trStr += '<td>失效</td>';
		}*/
		trStr += '<td>';
		if (canUpdate){
			trStr +='<a href="addUserInfo.jsp?userId='+ite.userId+'" data-toggle="modal" class="btn defined-role-btn" id="btn_edit_user_"'+ite.userId+'>修改</a>';
		}
		if (privilegeSet){
			trStr +='<a href="privilegeSet.jsp?userId='+ite.userId+'&account='+ite.account+'&userName=' +encodeURI(encodeURI(userName))+ '" data-toggle="modal" class="btn defined-role-btn" id="btn_edit_user_"'+ite.userId+'>权限设置</a>';
		}
		trStr +='<a href="userInfoDesc.jsp?userId='+ite.userId+'" class="btn defined-role-btn" >详情</a></td>';
		trStr += '</tr>';
		$("#listTable>tbody").append(trStr);
	});
}


/**
 * 用户删除。
 */
function removeAllUser() {
	var chk_value =[]; 
	$('input[name="check"]:checked').each(function(){ 
		chk_value.push($(this).val()); 
	}); 
	if (chk_value.length == 0) {
		$.sucmodal("提示", "请勾选要删除的用户",2000);
		return;
	}
	$.altmodal("删除", "您确定要删除所选的用户吗?",1000,function(){
		$.post(
			"userAction!removeUser.action",
			{comingParams:JSON.stringify(chk_value)},
			function(data){
				data = eval("("+data+")");
				if(data.result == "true"){
					$.sucmodal("提交成功", data.msg,function(){
						location.reload();
	            	});
				}else{
					$.sucmodal("提交失败", data.msg);
				}
			}
		);
	});
}

//初始化fileinput控件（第一次初始化）
function initFileInput(ctrlName, uploadUrl) {    
    var control = $('#' + ctrlName); 
/**
 * filepreajax
 filepreupload
 */
    control.fileinput({
        language: 'zh', //设置语言
        showPreview: false,
        uploadAsync: false,
        uploadUrl: uploadUrl, //上传的地址
        showCancel:false,
        showUploadedThumbs:false,
        allowedFileExtensions : ['xls', 'xlsx'],//接收的文件后缀
        showUpload: true, //是否显示上传按钮
        showCaption: true,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式          
        	enctype: 'multipart/form-data',
        	validateInitialCount:true,
        	maxFileCount:1
//        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>" 
    }).on('filepreajax', function(event, previewId, index) {
    	//文件上传前动作
        //console.log('File pre ajax triggered');
    }).on('fileuploaded', function(event,data, previewId, index) {
    	//文件上传前动作
        //console.log('File pre ajax triggered');
    }).on('filebatchuploadsuccess', function(event, data,
    		previewId, index) {
    	//var form = data.form, files = data.files, extra = data.extra,
    	response= eval("(" + data.response + ")");
    	if (response.result == "true"){
    		$.sucmodal("提示", response.msg, function() {
				location.href = "userManager.jsp";
			});
    	}else {
			alert("导入失败"+response.msg);
		}
    	//console.log('File uploaded triggered'); 
    	});;
}

function importUser(){
	/*$.ajax({
        cache: true,
        type: "POST",
        url:"userAction!uploadFile.action",
        data:$('#userInportForm').serialize(),// 你的formid
        async: false,
        error: function(request) {
            alert("Connection error");
        },
        success: function(data) {
            $("#commonLayout_appcreshi").parent().html(data);
        }
    });*/
	$('#userInportForm').submit();//提交表单
}